package com.morik.util;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

public class DwrMetaConverter {
    public static String createMeta(Class cls, Map heads) {
	Method methods[] = cls.getDeclaredMethods();
	String head = "{totalProperty:\"totalSize\",root:\"data\",id:\"id\",fields:[";
	StringBuilder sb = new StringBuilder(head);
	for (int i = 0; i < methods.length; i++) {
	    String mname = methods[i].getName();
	    String fname = DwrMetaConverter.uncapitalize(mname.substring(3));
	    Class rt = methods[i].getReturnType();
	    if (mname.substring(0, 3).equals("get")) {
		sb.append("{ name :\"" + fname + "\",");
		String h = (heads.get(fname) == null) ? fname : (String) heads
			.get(fname);
		sb.append(" _head :\"" + h + "\",");
		if (rt == Float.TYPE || rt == Float.class) {
		    sb.append("type :\"float\"}");
		} else if ((rt == Integer.TYPE || rt == Integer.class)
			|| (rt == Long.TYPE || rt == Long.class)) {
		    sb.append("type :\"int\"}");
		} else if (rt == String.class) {
		    sb.append("type :\"string\"}");
		} else if (rt == Boolean.TYPE || rt == Boolean.class) {
		    sb.append("type :\"boolean\"}");
		} else if (rt.isAssignableFrom(Date.class)) {
		    sb.append("type :\"date\"}");
		} else {
		    sb.deleteCharAt(sb.length() - 1);
		    sb.append("}");
		}
		sb.append(",");
	    }
	}
	sb.deleteCharAt(sb.length() - 1);
	sb.append("]}");
	System.out.println(sb.toString());
	return sb.toString();
    }

    public static String uncapitalize(String str) {
	int strLen;
	if (str == null || (strLen = str.length()) == 0) {
	    return str;
	}
	return new StringBuffer(strLen).append(
		Character.toLowerCase(str.charAt(0))).append(str.substring(1))
		.toString();
    }

    public static String createMeta(String name, Map map)
	    throws ClassNotFoundException {
	Class cls = Thread.currentThread().getContextClassLoader().loadClass(
		"com.data." + name);
	return createMeta(cls, map);
    }

    public static void main(String[] args) {
	try {
	    
	    Map m = new HashMap();
		m.put("id", "ID");
		m.put("comNum", "公司编号");
		m.put("comName", "公司名称");
		m.put("comAddress", "公司地址");	
	    System.out.println(new DwrMetaConverter().createMeta("Company", m));
	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	}
    }
}